package com.example.demo.Gmail.Handle;

import com.example.demo.Gmail.Excutor.AscWatchMailChange;
import com.example.demo.Gmail.Excutor.ThreadUpload;
import com.example.demo.Gmail.model.MessageModel;
import com.example.demo.Gmail.model.UserModel;
import com.example.demo.Gmail.service.BackendService;
import com.example.demo.Gmail.service.UserService;
import com.google.pubsub.v1.PubsubMessage;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;

public class WatchHandler {
    private static Logger logger = LoggerFactory.getLogger("WatchHandler");
    public void handler(PubsubMessage message, UserService userService, BackendService backendService) {
        UserModel user;
        List<Callable<Map<String,Set<String>>>> tasks = new ArrayList<>();
        JSONObject data= JSONObject.fromObject(message.getData().toStringUtf8());
        if (data.get("emailAddress")!=null){
            String emailAddress=data.get("emailAddress").toString();
            user= userService.getUser(emailAddress);
            AscWatchMailChange ascWatchMailChange=new AscWatchMailChange(user);
            try {
                Map map= ascWatchMailChange.call();
                this.importMongo(map,user,backendService);
            }catch (Exception e){
                logger.info(e.getMessage());
            }

        }
      }

      public void importMongo( Map<String, Set<String>>  map,UserModel user,BackendService backendService) throws InterruptedException, ExecutionException {
       //TODO
          List<Callable<MessageModel>> tasks = new ArrayList<>();
              for (String id:map.keySet()){
                  for (String emailId:map.get(id)){
                      //判断当前的id数据库是否存在，如果存在就不重新插入，否则就插入到本地数据库
                       if (backendService.getMessage(emailId,user.getEmailAddress())==null){
                           System.out.println("times");
                           Callable<MessageModel>  upload=   new ThreadUpload(id,user,emailId);
                           tasks.add(upload);
                       }
                  }
              }
          List<MessageModel> messageModels = new ArrayList<>();
          ExecutorService executorService = Executors.newFixedThreadPool(20);
          List<Future<MessageModel>> futures=executorService.invokeAll(tasks);
          for (Future<MessageModel> future:futures){
              messageModels.add(future.get());
          }
          executorService.shutdown();//关闭线程池
          if(messageModels.size()!=0&messageModels!=null){
              backendService.insertInbox(messageModels);
              System.out.println("你有新的添加信息");
          }else {
              return;
          }
      }
}
